package com.bearsadmin.controller;

import com.bearsadmin.common.Result;
import com.bearsadmin.service.UserService;
import com.bearsadmin.util.JwtUtil;
import com.bearsadmin.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 文件上传控制器
 *
 * @author Bears Admin
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    private final UserService userService;

    /**
     * 上传用户头像
     *
     * @param file    头像文件
     * @param request HTTP请求
     * @return 上传结果
     */
    @PostMapping("/upload/avatar")
    public Result<UserVO> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {

        // 从请求头获取用户ID
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 验证token并获取用户ID
        if (!JwtUtil.verifyToken(token)) {
            return Result.error("用户未登录或token已过期");
        }

        String username = JwtUtil.getUsername(token);
        if (username == null) {
            return Result.error("用户未登录");
        }

        // 通过用户名获取用户ID
        com.bearsadmin.entity.User user = userService.getUserByUsername(username);
        if (user == null) {
            return Result.error("用户不存在");
        }

        try {
            UserVO userVO = userService.uploadAvatar(user.getId(), file);
            return Result.success(userVO);
        } catch (Exception e) {
            log.error("头像上传失败", e);
            return Result.error("头像上传失败: " + e.getMessage());
        }
    }
}